package com.jinpin.oauth.init;

import com.jinpin.core.constant.RedisConstant;
import com.jinpin.oauth.entity.dto.PermissionDto;
import com.jinpin.oauth.entity.dto.RoleDto;
import com.jinpin.oauth.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

@Component
public class ResourceInit {

    private Map<String, List<String>> resourceRolesMap;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @PostConstruct
    public void initData() {
        List<PermissionDto> permissionAndRole = permissionMapper.getPermissionAndRole();

        // todo 从数据库读权限  url :  roles
        resourceRolesMap = new TreeMap<>();
        for (PermissionDto permissionDto : permissionAndRole) {
            resourceRolesMap.put(permissionDto.getPermission(),
                    permissionDto.getRoleStrList().stream()
                            .map(RoleDto::getRoleStr).collect(Collectors.toList()));
        }
        redisTemplate.opsForHash().putAll(RedisConstant.RESOURCE_ROLES_MAP, resourceRolesMap);
    }
}
